<?php

namespace App\Http\Controllers\Admin;

use App\Enums\AvailableStatus;
use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Partner;

class PartnerController extends Controller
{
    /** 列表查询 */
    public function index()
    {
        $query = Partner::query()
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 添加或修改 */
    public function store()
    {
        request()->validate([
            'name' => 'required',
        ]);
        $partnerName = request()->name;
        if (request()->id) {
            $partner = Partner::query()->find(request()->id);
            $partner->name = $partnerName;
            $partner->save();
        } else {
            $partner = new Partner();
            $partner->name = $partnerName;
            $partner->app_id = uniqid();
            $partner->app_secret = md5($partner->name . $partner->app_id);
            $partner->save();
        }
    }

    /** 删除 */
    public function destroy($id)
    {
        $agent = Partner::query()->find($id);
        $agent->delete();
    }

    /** 修改合作商状态 */
    public function changeStatus($id)
    {
        request()->validate([
            'status' => 'enum_value:' . AvailableStatus::class,
        ]);
        $agent = Agent::query()->find($id);
        $agent->status = request()->status;
        $agent->save();
    }
}
